<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-09-23 11:42
 *
 * 项目：rm  -  $  - paySdk.php
 *
 * 作者：liwei 
 */

namespace modules\levpays\modules\baidupay\sdk\sdk;

use Lev;
use lev\helpers\curlHelper;
use modules\levpays\modules\baidupay\sdk\baiduPayment;

!defined('INLEV') && exit('Access Denied LEV');


class paySdk
{
    public static $config = null;

    /**
     * 文档： https://dianshang.baidu.com/platform/doclist/index.html#!/doc/nuomiplus_1_guide/mini_program_cashier/standard_interface/tune_up.md
     * 文档： https://smartprogram.baidu.com/docs/develop/api/open/payment_swan-requestPolymerPayment/#%E6%96%B9%E6%B3%95%E5%8F%82%E6%95%B0
     * 文档： https://smartprogram.baidu.com/docs/develop/function/tune_up_2.0/
     * [createOrder 百度小程序支付创建订单]
     * @param $out_trade_no
     * @param $subject
     * @param $total_amount
     * @param string $body
     * @param array $order
     * @return array [type] [description]
     */

    public static function createOrder($out_trade_no, $subject, $total_amount, $body = '', $order = []) {
        $total_amount *= 100;

        baiduPayment::loadConfig();
        $config = static::$config;

        $requestParamsArr = array(

            'appKey' => $config['app_key'],

            'dealId' => $config['deal_id'],

            'tpOrderId' => $out_trade_no,

            'totalAmount' => $total_amount, //订单金额（单位：人民币分）。注：小程序测试包测试金额不可超过 1000 分

        );

        $rsaSign = RSASign::sign($requestParamsArr, $config['private_key']); // 声称百度支付签名

        $bizInfo = array(

            'tpData' => array(

                "appKey" => $config['app_key'],

                "dealId" => $config['deal_id'],

                "tpOrderId" => $out_trade_no,

                "rsaSign" => $rsaSign,

                "totalAmount" => $total_amount,

                "returnData" => '',

                "displayData" => array(

                    "cashierTopBlock" => array(

                        array(

                            [ "leftCol" => $subject, "rightCol" => $body ],

                            [ "leftCol" => Lev::arrv('leftColnum', $order, "数量"), "rightCol" => Lev::arrv('rightColnum', $order, 1) ],

                            [ "leftCol" => Lev::arrv('leftColamount', $order, "订单金额"), "rightCol" => $total_amount ]

                        ),

                        array(

                            [ "leftCol" => "服务地址", "rightCol" => "-" ],

                            [ "leftCol" => "服务时间", "rightCol" => date('Y/m/d H:i', Lev::$app['timestamp']) ],

                            [ "leftCol" => "服务人员", "rightCol" => Lev::arrv('miniName', $order, "帮帮帮网") ]

                        )

                    )

                ),

                "dealTitle" => $subject,

                "dealSubTitle" => $body,

                "dealThumbView" => "https://b.bdstatic.com/searchbox/icms/searchbox/img/swan-logo.png",

            ),

            "orderDetailData" => ''

        );

        $bdOrder = array(

            'dealId' => $config['deal_id'],

            'appKey' => $config['app_key'],

            'totalAmount' => $total_amount,

            'tpOrderId' => $out_trade_no,

            'dealTitle' => $body,

            'signFieldsRange' => 1,

            'rsaSign' => $rsaSign,

            'bizInfo' => json_encode($bizInfo),

        );

        return $bdOrder;

    }

    /**
     * [refund baidu支付退款]
     * @param $out_trade_no
     * @param $total_amount
     * @param string $body
     * @param array $order
     * @param int $type
     * @return mixed
     */

    public static function refund($out_trade_no, $total_amount, $body = '', $order = [], $type = 1)

    {

        $config = static::$config;

        $data = array(

            'access_token' => $order['access_token'], // 获取开发者服务权限说明

            'applyRefundMoney' => $total_amount, // 退款金额，单位：分。

            'bizRefundBatchId' => $out_trade_no, // 开发者退款批次

            'isSkipAudit' => 1, // 是否跳过审核，不需要百度请求开发者退款审核请传 1，默认为0； 0：不跳过开发者业务方审核；1：跳过开发者业务方审核。

            'orderId' => $order['order_id'], // 百度收银台订单 ID

            'refundReason' => $body, // 退款原因

            'refundType' => $type, // 退款类型 1：用户发起退款；2：开发者业务方客服退款；3：开发者服务异常退款。

            'tpOrderId' => $out_trade_no, // 开发者订单 ID

            'userId' => $order['user_id'], // 百度收银台用户 id

        );

        $array = ['errno'=>0, 'msg'=>'success', 'data'=> ['isConsumed'=>2] ];

        $url = 'https://openapi.baidu.com/rest/2.0/smartapp/pay/paymentservice/applyOrderRefund';

        $pm['url'] = $url;
        $pm['post'] = $data;
        $response = curlHelper::doCurl($pm);

        $result = json_decode($response, true);

// // 显示错误信息

// if ($result['msg']!='success') {

// return false;

// // die($result['msg']);

// }

        return $result;

    }

    /**

     * [notify 回调验证]

     * @return [array] [返回数组格式的notify数据]

     */

    public static function notify()

    {

        $data = $_POST; // 获取xml

        $config = static::$config;

        if (!$data || empty($data['rsaSign'])) die('暂无回调信息');

        $result = RSASign::checkSign($data, $config['public_key']); // 进行签名验证

// 判断签名是否正确 判断支付状态

        if ($result && $data['status']==2) {

            return $data;

        } else {

            return false;

        }

    }
}